package com.nbsaas.boot;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;

public class JdkWebSocketClient {
    public static void main(String[] args) throws Exception {
        // WebSocket 服务端地址（替换为实际地址）
        String wsUri = "wss://adminstore.saas.nbsaas.com/websocket"; // 测试用的回声服务

        // 创建 HttpClient
        HttpClient client = HttpClient.newHttpClient();

        // 构建 WebSocket 客户端
        WebSocket webSocket = client.newWebSocketBuilder()
                .buildAsync(URI.create(wsUri), new WebSocket.Listener() {

                    // 连接成功时触发
                    @Override
                    public void onOpen(WebSocket webSocket) {
                        System.out.println("连接已建立");
                        WebSocket.Listener.super.onOpen(webSocket);
                        // 连接成功后发送消息
                        webSocket.sendText("Hello WebSocket!", true);
                    }

                    // 接收文本消息
                    @Override
                    public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
                        System.out.println("收到消息：" + data);
                        // 可以在这里继续发送消息或关闭连接
                        if (data.toString().contains("echo")) {
                            webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "完成").join();
                        }
                        return WebSocket.Listener.super.onText(webSocket, data, last);
                    }

                    // 接收二进制消息
                    @Override
                    public CompletionStage<?> onBinary(WebSocket webSocket, ByteBuffer data, boolean last) {
                        System.out.println("收到二进制消息，长度：" + data.remaining());
                        return WebSocket.Listener.super.onBinary(webSocket, data, last);
                    }

                    // 连接关闭时触发
                    @Override
                    public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
                        System.out.println("连接关闭，状态码：" + statusCode + "，原因：" + reason);
                        return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
                    }

                    // 发生错误时触发
                    @Override
                    public void onError(WebSocket webSocket, Throwable error) {
                        System.err.println("发生错误：" + error.getMessage());
                        WebSocket.Listener.super.onError(webSocket, error);
                    }
                }).join(); // 阻塞等待连接建立

        // 阻塞主线程，防止程序退出（实际业务中根据需求调整）
        //Thread.sleep(5000);
    }
}
